package com.lazy.controller.student;


import com.lazy.constant.JwtClaimsConstant;
import com.lazy.dto.StudentDTO;
import com.lazy.dto.StudentLoginDTO;
import com.lazy.entity.Student;
import com.lazy.properties.JwtProperties;
import com.lazy.result.Result;
import com.lazy.service.StudentService;
import com.lazy.utils.JwtUtil;
import com.lazy.vo.StudentLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/student")
@CrossOrigin(origins = "http://localhost:8080")
/*
  学生相关接口
 */
@Slf4j
public class StudentController {

    @Autowired
    private StudentService studentService;
    @Autowired
    private JwtProperties jwtProperties;


    /**
     * 学生登录
     * @param studentLoginDTO
     * @return
     */
    @PostMapping("/login")
    public Result<StudentLoginVO> login(@RequestBody StudentLoginDTO studentLoginDTO) {
        // 记录学生登录信息
        log.info("学生登录：{}", studentLoginDTO);

        // 调用学生服务的登录方法，验证学生登录信息并获取学生对象
        Student student = studentService.login(studentLoginDTO);

        // 创建一个映射，用于存储JWT中的自定义信息
        Map<String, Object> claims = new HashMap<>();
        // 将学生ID放入JWT的自定义信息中，以便在JWT中标识学生身份
        claims.put(JwtClaimsConstant.STUDENT_ID, student.getId());

        // 使用JWT工具类创建JWT令牌，包含学生ID、JWT的密钥和过期时间
        String token = JwtUtil.createJWT(
                jwtProperties.getStudentSecretKey(),
                jwtProperties.getStudentTtl(),
                claims);

        // 构建学生登录响应对象，包含学生ID、用户名和生成的JWT令牌
        StudentLoginVO employeeLoginVO = StudentLoginVO.builder()
                .id(student.getId())
                .username(student.getUsername())
                .token(token)
                .build();

        // 返回成功的结果，包含学生登录响应对象
        return Result.success(employeeLoginVO);
    }

    @PostMapping("/register")
    public Result<String> register(@RequestBody StudentDTO studentDTO) {
        log.info("学生注册：{}", studentDTO);
        studentService.register(studentDTO);
        return Result.success();
    }

    @GetMapping("/selectById")
    public Result<Student> selectById(){
        Student student = studentService.selectById();
        return Result.success(student);
    }
}
